package com.hcb.micro.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import com.hcb.micro.bean.base.OutHead;
import com.hcb.micro.dto.ReturnUploadImage;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("fileTX")
public class FileTXController{
    private static String accessKeyId="rvCyNiasyIq1JGHD";
    private static String accessKeySecret="VzKWi0s3y3CXSzqKr7b8E1NBmYGNgo";
    private static String bucketName="bucket20160601";
    private static String endpoint="http://oss-cn-hangzhou.aliyuncs.com";
    
    
    private final String imageUrl="http://shangmenhuigou-1256139664.cos.ap-shanghai.myqcloud.com/";
    /** 根目录 */
	
	//private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
	//private static String accessKeyId = "LTAIEBYdbuuY3HCI";
	//private static String accessKeySecret = "2U6js4HyZzNV7BUB01nE2hEyx5ACh1";
	//private static String bucketName = "feichs";
	//public static final String imageUrl = "http://feichs.oss-cn-beijing.aliyuncs.com/";
/*	private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
	private static String accessKeyId = "rvCyNiasyIq1JGHD";
	private static String accessKeySecret = "VzKWi0s3y3CXSzqKr7b8E1NBmYGNgo";
	private static String bucketName = "bucket20160601";
	public static final String imageUrl = "http://bucket20160601.oss-cn-hangzhou.aliyuncs.com/";
*/	
	/*@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFile() {
		JSONObject json = new JSONObject();
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if (bodyInfo.get("file") == null || "".equals(bodyInfo.get("file"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		BufferedImage image = null;
		String imageResult = "";
		try {
			
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	        MultipartFile multipartFile = multipartRequest.getFile("file");
			
	       	image = ImageIO.read(multipartFile.getInputStream()); //读取连接的流，赋值给BufferedImage对象
	       	
	       	Random random = new Random();
	    	String number = Long.toHexString(Long.valueOf(random.nextInt(10) + "" + System.currentTimeMillis() + "" + random.nextInt(10)));
	       	
   			String imageName = "image"+number+".jpg";
			OSSUPUtil.uploadIMG(imageName,image);
			imageResult = "http://bucket20160601.oss-cn-hangzhou.aliyuncs.com/"+imageName;
		} catch (Exception e) {
			e.printStackTrace();
	    	json.put("result", "1");
			json.put("description", "文件上传失败");
			return buildReqJsonObject(json);
		}     
		
		json.put("imageResult", imageResult);
    	json.put("result", "0");
		json.put("description", "文件上传成功");
		
		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "uploadImage1", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImage() {
		JSONObject json = new JSONObject();
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if (bodyInfo.get("file") == null || "".equals(bodyInfo.get("file"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		Random random = new Random();
		String number = Long.toHexString(Long.valueOf(random.nextInt(10) + "" + System.currentTimeMillis() + "" + random.nextInt(10)));
		BufferedImage image = null;
		String imageResult = "";
		try {
			URL u = new URL(bodyInfo.getString("file"));
			image = ImageIO.read(u);
   			String imageName = "CC_PRODUCT_"+number+"1.jpg";
			OSSUPUtil.uploadIMG(imageName,image);
			imageResult = "http://bucket20160601.oss-cn-hangzhou.aliyuncs.com/"+imageName;
		} catch (Exception e) {
			e.printStackTrace();
	    	json.put("result", "1");
			json.put("description", "文件上传失败");
			return buildReqJsonObject(json);
		}
		
		json.put("imageResult", imageResult);
    	json.put("result", "0");
		json.put("description", "文件上传成功");
		
		return buildReqJsonObject(json);
	}*/
	
	//上传文件
    @RequestMapping(value = "uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
    	JSONObject json = new JSONObject();
    	String fileUrl = "";
    	String loghead = "通用接口-上传图片:";
        // 判断文件是否为空
        if (!file.isEmpty()) {
        	
            //校验文件类型
            String originName = file.getOriginalFilename();
            
            String returnUrl80 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
            String returnUrl = request.getScheme() + "://" + request.getServerName() + request.getContextPath() +"/upload/imgs/";//存储路径
            String path = request.getSession().getServletContext().getRealPath("upload/imgs"); //文件存储位置
            String fileF = originName.substring(originName.lastIndexOf("."), originName.length());//文件后缀
            
            System.out.println(fileF+"----fileF----"+originName+"--originName-------"+path+"---path---"+returnUrl);
            //先判断文件是否存在
           
           
            String[] types = originName.split("\\.");
            String origin = types[0];
            String type = null == types[types.length - 1] ? "" : types[types.length - 1];
            
            Random random = new Random();
	    	String number = Long.toHexString(Long.valueOf(random.nextInt(10) + "" + System.currentTimeMillis() + "" + random.nextInt(10)));
	    	String fileName = origin + '-' + number + fileF; //新的文件名
	    	originName=number+fileF;//新的文件名
	    	 File file1 =new File(path+"/"); 
	    	 File file2 =new File(returnUrl+"/"); 
	            //如果文件夹不存在则创建    
	            if(!file1.exists()  && !file1.isDirectory()){     
	                file1.mkdirs();  
	            }
	            if(!file2.exists()  && !file2.isDirectory()){     
	                file2.mkdirs();  
	            }
	            File targetFile = new File(file1, fileName);
	            File targetFile2 = new File(file2, fileName);
	            try {
	                file.transferTo(targetFile);
	                file.transferTo(targetFile2);

	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            System.out.println(targetFile+"---targetFile------");
	            System.out.println(targetFile2+"---targetFile2------");
	            
	            
	    	String contentType = file.getContentType();
           
            long fileSize = file.getSize();  
            System.out.println(loghead + "fileInfo:fileName=" + fileName + "&fileSize=" + fileSize);  
            if (fileSize <= 0) {
            	System.out.println(loghead + "上传失败:文件为空");  
                json.put("result", "1");
                json.put("description", "上传失败:文件为空");
                return buildReqJsonObject(json);
            } else if (fileSize > (500 * 1024)) {  
            	System.out.println(loghead + "上传失败:文件大小不能超过500K");  
                json.put("result", "1");
                json.put("description", "上传失败:文件大小不能超过500K,请压缩后上传");
                return buildReqJsonObject(json);
            } 
         // 1 初始化用户身份信息(secretId, secretKey)
            COSCredentials cred = new BasicCOSCredentials("AKID7CHNXjOfOwMi40s2paH9vnbDFD6xL5Od", "T7nZHqEcp05A7uWK0XzIPLpUjsv1xkMo");
            // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
            // 3 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);
            // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
            String bucketName = "shangmenhuigou-1256139664";
            
             // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
	         // 对象键（Key）是对象在存储桶中的唯一标识。例如，在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中，对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
	         String key = fileName;
	         PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, targetFile2);
	         System.out.println("new PutObjectRequest---------");
	         PutObjectResult putObjectResult = cosClient.putObject(bucketName, key, targetFile2);
	         System.out.println("putObject---------");
	         String etag = putObjectResult.getETag();
	         System.out.println(etag+"------------------etag");
           
            // 关闭client
         	cosClient.shutdown();
            fileUrl = imageUrl + URLEncoder.encode(fileName + "." + type, "UTF-8");
            json.put("fileUrl", imageUrl + URLEncoder.encode(fileName + "." + type, "UTF-8"));
            json.put("result", "0");
            json.put("description", "1");
            return buildReqJsonObject(json);
        } else {
        	json.put("result", "1");
            json.put("description", "1");
            return buildReqJsonObject(json);
        }
    }
	
    
    protected String buildReqJsonObject(Object msgs) {
    	com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
		jo.put("head", getDefaultOutHead());
		jo.put("body", msgs);
		return jo.toJSONString();
	}
    
    protected OutHead getDefaultOutHead() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String time = format.format(date);
		return new OutHead().setReturnCode("000").setReturnDescription("验证通过").setSysTime(time);
	}
	/**
	 * lxy 微信获取 再上传 
	 * @param request
	 * @param file
	 * @return
	 */
	/*@RequestMapping("imageweixin")
	@ResponseBody
	public String weixinimg(HttpServletRequest request, HttpServletResponse response, HttpSession session,String serverId) {
		if ( serverId!=null ) {
		    String accessToken=WeixinMessageDigestUtil.getAccessToken(CommonConstant.appid, CommonConstant.secret);
			// 创建OSSClient实例
			String bucketName = "bucket20160601";
			OSSClient ossClient = new OSSClient("http://oss-cn-hangzhou.aliyuncs.com", "rvCyNiasyIq1JGHD","VzKWi0s3y3CXSzqKr7b8E1NBmYGNgo");
			String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";  
			requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", serverId);  
			try {
				String attachmentUuid = this.generateFileName(serverId);
				URL url = new URL(requestUrl);  
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
				conn.setDoInput(true);  
				conn.setRequestMethod("GET");  
				conn.connect();
				InputStream input = conn.getInputStream();
				ObjectMetadata metadata = new ObjectMetadata();
				metadata.setContentType(conn.getContentType());
				PutObjectResult result = ossClient.putObject(bucketName, attachmentUuid+"." +"jpg",input, metadata);
	        	  
				String  imgurl=   "http://"+bucketName+".oss-cn-beijing.aliyuncs.com/"+attachmentUuid+"." +"jpg";
				System.out.println("imgurlNum---------------+++++++--------------:"+imgurl);
				return imgurl;
			} catch (Exception e) {
				//handle exception
				e.printStackTrace();
			}
		}
		return "no";
	}*/
	
	/*@RequestMapping(value = "downloadFile", method = RequestMethod.POST)
	@ResponseBody
	public String downloadFile() {
		JSONObject json = new JSONObject();
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if (bodyInfo.get("imageUrl") == null || "".equals(bodyInfo.get("imageUrl"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		String imageResult = "";
		try {
			imageResult = OSSUPUtil.getImgURl(bodyInfo.getString("imageUrl"));
		} catch (Exception e) {
			e.printStackTrace();
	    	json.put("result", "1");
			json.put("description", "文件下载失败");
			return buildReqJsonObject(json);
		}     
		
		json.put("tempFilePath", imageResult);
    	json.put("result", "0");
		json.put("description", "文件下载成功");
		
		return buildReqJsonObject(json);
	}*/
    
 // 上传文件
 	@RequestMapping(value = "upload", method = RequestMethod.POST)
 	@ResponseBody
 	public String uploadImage(HttpServletRequest request, HttpServletResponse response)
 			throws IllegalStateException, IOException {
 		response.setContentType("text/html;charset=UTF-8");

 		ServletContext servletContext = request.getSession().getServletContext();
 		System.out.println("servletContext:" + servletContext);
 		String uploadPath = servletContext.getRealPath("/") + "ueditor/jsp/upload/image/";
 		System.out.println("uploadPath:" + uploadPath);
 		ReturnUploadImage rui = null;// 这个是UEditor需要的返回值内容，UEditor要的返回值需要封装成Json格式
 		// 转型为MultipartHttpRequest：
 		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 		// 获得文件：
 		MultipartFile file = multipartRequest.getFile("upfile"); // UEditor传到后台的是这个upfile，其他的文件上传，应该也差不多是这个，还没去研究，断点一下就知道了
 		String OriginalFilename = file.getOriginalFilename();

 		System.out.println("OriginalFilename:"+OriginalFilename);
 		
 		String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
 		String newname = "";
 		SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
 		String times = sf_.format(new Date());
 		newname = times + (int) (Math.random() * (99999 - 10000) + 10000) + "." + fileSuffix;
 		// 写入文件
 		File imageFile = new File(uploadPath, newname);
 		file.transferTo(imageFile);
 		// 现在获取了File接下来要上传到OSS上
 		if (imageFile != null) {
 			rui = new ReturnUploadImage();
 			rui.setTitle(imageFile.getName());// 这里需要设置文件名称如：xxx.jpg
 			rui.setOriginal(imageFile.getName());// 这里需要设置文件名称如：xxx.jpg
 			// 判断文件是否为图片文件
 			// 上传文件(先保存到磁盘，这样对磁盘比较伤，每次上传都要先保存到磁盘，然后再删除)
 			String str = partUpload(uploadPath + newname, newname);// 这里是自己封装的OSS，上传到OSS上面
 			System.out.println("OSSstr:" + str);
 			rui.setUrl(str);
 			rui.setState("SUCCESS");// 这里上传成功的话一定要设置大写的 //
 									// SUCCESS，失败还没测试，猜应该是FAIL，回头再去官网找找
 			// 判断临时存放的文件是否存在
 			if (imageFile.exists()) {
 				// 删除临时存放的文件
 				imageFile.delete();
 			}
 		}
 		String result = JSON.toJSONString(rui);// 这边就是为了返回给UEditor做的格式转换
 		System.out.println("result:" + result);
 		response.getWriter().write(result);
 		return null;
 	}
 	
 	/**
      * 断点续传上传
      *
      * @param fileAbsolutePath
      * @return
      */
     public static String partUpload(String fileAbsolutePath, String fileName) {//, String packageName
     // 设置断点续传请求
     UploadFileRequest uploadFileRequest = new UploadFileRequest("feichs", fileName);
     // 指定上传的本地文件
     uploadFileRequest.setUploadFile(fileAbsolutePath);
     // 指定上传并发线程数
     uploadFileRequest.setTaskNum(8);
     // 指定上传的分片大小
     uploadFileRequest.setPartSize(1 * 1024 * 1024);
     // 开启断点续传
     uploadFileRequest.setEnableCheckpoint(true);
     // 断点续传上传
     ///client.uploadFile(uploadFileRequest);
     try {
             // 断点续传上传
     		// 创建OSSClient实例
 			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
             UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
             return null != uploadResult ? uploadResult.getMultipartUploadResult().getLocation() : "";


         } catch (Throwable throwable) {
             throwable.printStackTrace();
             return "";
         }
     }
}
